package cn.pconline.autoclub.web.wap;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.CityDyna;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubDyna;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.EffectiveDynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.StatService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.CommentDynaUtils;
import cn.pconline.autoclub.web.UserAuth;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * WAP版相关URL
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
@Controller
@RequestMapping("/wap/dyna")
public class DynaAction {

    @Autowired
    private UserAuth userAuth;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ClubService clubService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private StatService statService;
    @Autowired
    private EffectiveDynaService dynaService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private ActivityService activityService;
    private static final int MAX_PAGE_SIZE = 100;
    protected static final Logger log = LoggerFactory.getLogger(DynaAction.class);

    private String redirect404(HttpServletResponse response) {
        try {
            response.sendError(404);
        } catch (Exception ex) {
            log.error("redirect404 fail!", ex);
        }
        return "redirect:http://m.pcauto.com.cn/x/404/";
    }

    private void printMsg(HttpServletResponse resp, String str, String callback) {
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("response输出出错了", ex);
        }
    }

    /**
     * 动态详细页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/dynaDetail", method = RequestMethod.GET)
    public String dynaDetail(HttpServletRequest request, HttpServletResponse response) {
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        if (0 == clubId || dynaInfoId == 0) {
            return redirect404(response);
        }
        ClubDyna clubDyna = dynaService.findClubDynaById(dynaInfoId, clubId);
        if (clubDyna == null || DynaInfo.isTopic(clubDyna.getType())
                || clubDyna.getStatus() == ClubDyna.STATUS_DELETE) {
            //帖子动态没有详情页
            return redirect404(response);
        }
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, clubDyna.getCreateDate());
        if (dynaInfo == null) {
            log.error("车友会动态索引表有脏数据[clubId,dynaInfoId][{},{}]，对应的动态不存在", clubId, dynaInfoId);
            return redirect404(response);
        }
        dynaService.filterImages(dynaInfo);//过滤掉不合法的图片
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            return redirect404(response);
        }
        String content = dynaInfo.getContent();
        if (dynaInfo.getType() == DynaInfo.TYPE_PICTURE) {
            Album a = albumService.getAlbumById(dynaInfo.getTargetId());
            if (a == null) {
                log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(albumId):{}]", dynaInfo.getDynaInfoId(), dynaInfo.getClubId(), dynaInfo.getTargetId());
                return redirect404(response);
            }
            request.setAttribute("album", a);
            request.setAttribute("pictureNum", dynaInfo.getPictureNum());
        }else if(dynaInfo.getType() == DynaInfo.TYPE_COMMENT){
            content = (WebUtils.dynaSubjectContent(systemConfig.getWapRoot(), WebUtils.transformToBBSFace(CommentDynaUtils.appendUrlUBB(dynaInfo.getContent())), dynaInfo.getSubjectIds()));
        }

        User user = userAuth.getUser(request, response);
        request.setAttribute("clubId", clubId);
        request.setAttribute("user", user);
        request.setAttribute("isMember", memberService.isClubMember(user.getUid(), club.getClubId()));
        request.setAttribute("club", club);
        request.setAttribute("imagesLength", dynaInfo.getImages() == null ? 0 : dynaInfo.getImages().size());
        request.setAttribute("dynaInfo", dynaInfo);
        request.setAttribute("content", content);
        return "/template/wap/dyna/detail";
    }

    /**
     * 动态详细页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/tongChenDynaDetail", method = RequestMethod.GET)
    public String tongChenDynaDetail(HttpServletRequest request, HttpServletResponse response) {
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        long provinceId = WebUtils.paramLong(request, "provinceId", 0);
        long cityId = WebUtils.paramLong(request, "cityId", 0);
        if (0 == provinceId) {
            return redirect404(response);
        }
        CityDyna cityDyna = dynaService.findCityDynaById(dynaInfoId, provinceId, cityId);
        if (cityDyna == null || DynaInfo.isTopic(cityDyna.getType())
                || cityDyna.getStatus() == ClubDyna.STATUS_DELETE) {
            //帖子动态没有详情页
            return redirect404(response);
        }
        DynaInfo dynaInfo = dynaService.findDynaById(dynaInfoId, cityDyna.getCreateDate());
        if (dynaInfo == null) {
            log.error("车友会动态索引表有脏数据[provinceId,cityId,dynaInfoId][{},{}]，对应的动态不存在", provinceId, cityId, dynaInfoId);
            return redirect404(response);
        }
        dynaService.filterImages(dynaInfo);//过滤掉不合法的图片
        User user = userAuth.getUser(request, response);
        request.setAttribute("user", user);
        request.setAttribute("isMember", false);
        request.setAttribute("imagesLength", dynaInfo.getImages() == null ? 0 : dynaInfo.getImages().size());
        request.setAttribute("dynaInfo", dynaInfo);
        request.setAttribute("referType", 1);
        return "/template/wap/dyna/detail";
    }

    /**
     * 动态回复列表接口 请求参数：dynaInfoId
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getReplyList")
    @ResponseBody
    public void getReplyList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        long dynaInfoId = WebUtils.paramLong(request, "dynaInfoId", 0L);
        int pageSize = WebUtils.paramInt(request, "pageSize", 15, 1, MAX_PAGE_SIZE);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int isTransFace = WebUtils.paramInt(request, "isTransFace", 0);
        JSONObject obj = new JSONObject();
        JSONArray arr = new JSONArray();
        int pageCount = 0;
        int sourceAgent = 2;
        if (dynaInfoId != 0) {
            Pager<DynaReply> pager = dynaService.getReplyListByDynaInfoId(dynaInfoId, pageNo, pageSize);
            if (pager != null) {
                for (DynaReply info : pager.getResultList()) {
                    JSONObject o = new JSONObject();
                    o.put("userId", info.getCreateBy());
                    o.put("dynaInfoId", info.getDynaInfoId());
                    o.put("replyId", info.getDynaReplyId());
                    o.put("createDate", DateUtils.format(info.getCreateAt(), "yyyy-MM-dd"));
                    o.put("myIcon", WebUtils.face(info.getCreateBy(), 50));
                    o.put("myIconUrl", systemConfig.getUcWapRoot() + "/" + info.getCreateBy() + "/");
                    o.put("nickName", EncodeUtils.encodeForHTML(info.getCreateName()));
                    o.put("toReply", info.getPostToNickName());
                    o.put("toReplyUrl", systemConfig.getUcWapRoot() + "/" + info.getPostToUserId() + "/");
                    o.put("time", DateUtils.format(info.getCreateDate(), "MM-dd HH:mm"));
                    o.put("des", isTransFace == 1 ? WebUtils.transformToBBSFace(cn.pconline.autoclub.util.EncodeUtils.encodeForHTML(info.getContent(), sourceAgent)) : cn.pconline.autoclub.util.EncodeUtils.encodeForHTML(info.getContent(), sourceAgent));
                    arr.add(o);
                }
                obj = pager.toJSONObject(arr);
                pageCount = pager.getPageCount();
            }
        }
        obj.put("pageCount", pageCount);
        obj.put("list", arr);
        printMsg(response, obj.toJSONString(), callback);
    }

    /**
     * 发留言动态的页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/postDyna", method = RequestMethod.GET)
    public String postDyna(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long provinceId = WebUtils.paramLong(request, "provinceId", 0);
        long cityId = WebUtils.paramLong(request, "cityId", 0);
        request.setAttribute("provinceId", provinceId);
        request.setAttribute("cityId", cityId);
        if (provinceId > 0 && cityId > 0) {  //同城页面跳转过来的
            String resultUri = "tongcheng";
            request.setAttribute("resultUri", resultUri);
            request.setAttribute("resultType", 1);
        }
        return "/template/wap/dyna/post";
    }

    /**
     * 分页获取车友会最新动态(WAP首页调用)
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/pageDynaList", method = RequestMethod.GET)
    public void pageDynaList(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 10, 1, 100);
        int source_agent = WebUtils.paramInt(req, "source_agent", 2);
        String callback = WebUtils.param(req, "callback", "");
        int isTranceFace = WebUtils.paramInt(req, "isTranceFace", 0);
        JSONObject obj = new JSONObject();
        JSONArray array = new JSONArray();
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            obj.put("code", -1);
            obj.put("message", "clubId有误");
            printMsg(resp, obj.toJSONString(), callback);
            return;
        }
        Pager<DynaInfo> pager = dynaService.getDynaListByClubIdTypes(clubId, pageNo, pageSize, DynaInfo.TYPE_TOPIC, DynaInfo.TYPE_COMMENT, DynaInfo.TYPE_QUESTION);

        obj.put("pageCount", pager == null ? 0 : pager.getPageCount());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (pager != null && pager.getResultList() != null && pager.getResultList().size() > 0) {
            for (DynaInfo dynaInfo : pager.getResultList()) {
                JSONObject dynaObject = new JSONObject();
                dynaObject.put("dynaInfoId", dynaInfo.getDynaInfoId());
                dynaObject.put("createDate", sdf.format(dynaInfo.getCreateDate()));
                dynaObject.put("myIcon", WebUtils.face(dynaInfo.getCreateBy(), 70));
                dynaObject.put("myIconUrl", systemConfig.getUcWapRoot() + "/" + dynaInfo.getCreateBy() + "/");
                dynaObject.put("nickName", EncodeUtils.encodeForHTML(userService.findUser(dynaInfo.getCreateBy()).getNickname(), source_agent));
                dynaObject.put("isTie", dynaInfo.isTopic());
                dynaObject.put("isJing", dynaInfo.getPick() == DynaInfo.PICK_YES);
                dynaObject.put("isJian", dynaInfo.getRecommend() == DynaInfo.RECOMMEND_YES);
                String content = EncodeUtils.encodeForHTML(dynaInfo.isTopic() ? dynaInfo.getTitle() : dynaInfo.getContent(), source_agent);
                if (dynaInfo.getType() == DynaInfo.TYPE_COMMENT) {
                    dynaObject.put("des", isTranceFace == 0 ? content : WebUtils.dynaSubjectContent(systemConfig.getWapRoot(),
                            WebUtils.transformToBBSFace(dynaInfo.getContent()), dynaInfo.getSubjectIds()));
                } else if (dynaInfo.isTopic()) {
                    dynaObject.put("des", isTranceFace == 0 ? content : WebUtils.transformToBBSFaceThenLimit(content, 120));
                } else {//暂支持返回说说，普通帖子，提问帖子的动态
                    continue;
                }
                if (dynaInfo.isTopic()) {
                    dynaObject.put("desUrl", systemConfig.getBbsWapRoot() + "/topic-" + dynaInfo.getTopicId() + ".html");
                    dynaObject.put("topicId", dynaInfo.getTopicId());
                    dynaObject.put("fid", dynaInfo.getForumId());
                } else {
                    dynaObject.put("desUrl", systemConfig.getWapRoot() + "/" + club.getClubUrl() + "/dt/" + dynaInfo.getDynaInfoId() + "/");
                }
                dynaObject.put("time", sdf.format(dynaInfo.getCreateDate()));
                dynaObject.put("count", dynaInfo.getPostCount());
                JSONArray images = new JSONArray();
                List<DynaImage> list = dynaInfo.getImages();
                if (list != null && list.size() > 0) {
                    int len = list.size();
                    for (DynaImage image : list) {
                        JSONObject imgObj = new JSONObject();
                        if (len <= 9 && len > 1) {
                            imgObj.put("width", 74);
                            imgObj.put("height", 74);
                            imgObj.put("smaPic", WebUtils.transPicUrl(image.getUrl500x500(), 150, 150));
                            imgObj.put("bigPic", image.getUrl400x400());
                        } else {
                            float width = image.getWidth();
                            float height = image.getHeight();
                            if (width > height) {
                                if (height < 90) {
                                    if (width > 300) {
                                        height = 90;
                                        width = 300;
                                    } else {
                                        height = height / (width / 300);
                                        width = 300;
                                    }
                                } else {
                                    height = height / (width / 300);
                                    width = 300;
                                }
                            } else if (height > width) {
                                if (width < 90) {
                                    if (height > 300) {
                                        height = 90;
                                        width = 300;
                                    } else {
                                        width = width / (height / 300);
                                        height = 300;
                                    }
                                } else {
                                    width = width / (height / 300);
                                    height = 300;
                                }
                            } else if (width == height) {
                                height = 300;
                                width = 300;
                            }
                            imgObj.put("width", (int) width / 2);
                            imgObj.put("height", (int) height / 2);
                            imgObj.put("smaPic", WebUtils.transPicUrl(image.getUrl500x500(), (int) width, (int) height));
                            imgObj.put("bigPic", image.getUrl400x400());
                        }
                        images.add(imgObj);
                    }
                }
                dynaObject.put("piclist", images);
                array.add(dynaObject);
            }
        }
        obj.put("list", array);
        printMsg(resp, obj.toJSONString(), callback);
    }
}
